<template>
  <view class="mine-container">
    <!-- 1. 顶部导航栏 -->
    <view class="top-nav">
      <text class="nav-title">我的</text>
    </view>

    <!-- 2. 用户信息区 -->
    <view class="user-info-wrap">
      <view class="user-info">
        <image 
          :src="userInfo.pic || '/static/default-avatar.png'" 
          class="user-avatar"
          mode="widthFix"
        ></image>
        
        <view class="name-id-area">
          <text v-if="!isLogin" class="unlogin-text">未登录</text>
          <text v-else class="login-username">{{ userInfo.userName || '普通用户' }}</text>
          <text v-if="isLogin" class="user-id">ID: {{ userInfo.id || '未知' }}</text>
        </view>
      </view>
    </view>

    <!-- 3. 我的评价卡片 -->
    <view class="evaluate-card" v-if="isLogin">
      <view class="card-header">
        <text class="card-title">我的评价</text>
        <text class="view-all" @click="toEvaluatePage">查看全部</text>
      </view>

      <view class="loading-state" v-if="evaluateLoading">
        <uni-icons type="loading" size="30" color="#5555ff" spin></uni-icons>
        <text class="loading-text">加载评价中...</text>
      </view>
      
      <view class="evaluate-list" v-else-if="realEvaluateList.length > 0">
        <view class="evaluate-item" v-for="(item, index) in realEvaluateList" :key="index">
          <view class="order-brief">
            <text class="order-title">{{ item.orderTitle || '未命名工单' }}</text>
            <text class="order-type">{{ item.orderTypeText || '未知类型' }}</text>
          </view>
          
          <view class="evaluate-header">
            <text class="taker-avatar">{{ item.orderTakerName.charAt(0) }}</text>
            <view class="evaluate-info">
              <text class="taker-name">{{ item.orderTakerName || '匿名接单员' }}</text>
              <view class="star-rating small">
                <text class="star" v-for="i in 5" :key="i" :class="{ active: i <= item.rating }">★</text>
              </view>
            </view>
            <text class="evaluate-time">{{ formatDate(item.createTime) }}</text>
          </view>
          
          <text class="evaluate-content">{{ item.comment || '无评价内容' }}</text>
        </view>
      </view>
      
      <view class="empty-evaluate" v-else>
        <text class="empty-icon">⭐</text>
        <text class="empty-text">暂无评价，快去评价工单吧～</text>
      </view>
    </view>

    <!-- 4. 功能列表（强制显示退出按钮） -->
    <view class="function-list">
      <view class="function-item" @click="toAbout">
        <text class="item-text">关于我们</text>
      </view>
      <view class="function-item" @click="toEditInfo">
        <text class="item-text">编辑个人信息</text>
      </view>
      <view class="function-item" @click="toMyOrders">
        <text class="item-text">我的工单</text>
      </view>
      <view class="function-item" @click="toSetting">
        <text class="item-text">设置</text>
      </view>
      <view class="function-item" @click="toEvaluatePage" v-if="isLogin">
        <text class="item-text">评价管理</text>
      </view>
      <!-- 退出登录：强制渲染 -->
      <view class="function-item logout-item" @click="handleLogout">
        <text class="item-text logout-text">退出登录</text>
      </view>
    </view>

    <!-- 5. 底部导航 -->
    <bottom-nav :current-path="currentPagePath" class="fixed-bottom-nav"></bottom-nav>
  </view>
</template>

<script>
import bottomNav from '@/pages/components/bottom-nav/bottom-nav.vue';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';

export default {
  components: { bottomNav, uniIcons },
  data() {
    return {
      userInfo: {},
      isLogin: false,
      currentPagePath: '/pages/User/profile/profile',
      realEvaluateList: [],
      evaluateLoading: false,
      evaluateParams: {
        pageNo: 1,
        pageSize: 3
      }
    };
  },
  onLoad() {
    this.initUserInfo();
    this.getMyEvaluateList();
  },
  onShow() {
    this.initUserInfo();
    this.getMyEvaluateList();
  },
  methods: {
    initUserInfo() {
      const token = uni.getStorageSync('token');
      const cacheUserInfo = uni.getStorageSync('userInfo') || {};
      const userId = cacheUserInfo.id;

      this.isLogin = !!token && !!userId;
      this.userInfo = cacheUserInfo;

      if (this.isLogin && userId) {
        this.fetchUserDetail(userId);
      }
    },

    fetchUserDetail(userId) {
      uni.request({
        url: 'http://localhost:6013/order-client/api/customerInfo/getByUserId',
        method: 'POST',
        data: { userId },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': `Bearer ${uni.getStorageSync('token')}`
        },
        success: (res) => {
          if (res.data.code === 0 && res.data.data) {
            this.userInfo = { ...this.userInfo, ...res.data.data };
            uni.setStorageSync('userInfo', this.userInfo);
          } else {
            uni.showToast({ title: '获取用户数据失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '网络错误，数据加载失败', icon: 'none' });
        }
      });
    },

    async getMyEvaluateList() {
      const token = uni.getStorageSync('token');
      if (!this.isLogin || !token) return;

      this.evaluateLoading = true;
      try {
        const response = await uni.request({
          url: 'http://localhost:6013/order-client/api/customerFeedback/queryPageList',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Token': token
          },
          data: this.evaluateParams
        });

        const resData = response.data || {};
        if (resData.code !== 0) {
          throw new Error(resData.msg || '获取评价失败');
        }

        const pageData = resData.data || {};
        const newEvaluates = pageData.records || [];

        this.realEvaluateList = newEvaluates.map(item => ({
          orderTakerName: (item.workOrderInfo && item.workOrderInfo.employeeName) || '匿名接单员',
          rating: item.rating || 0,
          createTime: item.createTime || '',
          comment: item.comment || '无评价内容',
          orderTitle: (item.workOrderInfo && item.workOrderInfo.title) || '未命名工单',
          orderTypeText: (item.workOrderInfo && this.mapOrderType(item.workOrderInfo.type)) || '未知类型'
        }));

      } catch (error) {
        let errMsg = '获取评价失败，请重试';
        if (error.message.includes('登录已过期')) {
          errMsg = '登录已过期，请重新登录';
          uni.removeStorageSync('token');
          this.isLogin = false;
          setTimeout(() => uni.redirectTo({ url: '/pages/login/login' }), 1500);
        }
        uni.showToast({ title: errMsg, icon: 'none' });
      } finally {
        this.evaluateLoading = false;
      }
    },

    mapOrderType(type) {
      const typeMap = { 1: '维修', 2: '安装', 3: '咨询', 4: '保养' };
      return typeMap[type] || '未知类型';
    },

    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    toAbout() {
      uni.navigateTo({ url: '/pages/User/mine/about' });
    },
    toEditInfo() {
      uni.navigateTo({
        url: `/pages/User/profile/personal-info?userInfo=${encodeURIComponent(JSON.stringify(this.userInfo))}`
      });
    },
    toMyOrders() {
      uni.navigateTo({ url: '/pages/User/workorder/list' });
    },
    toSetting() {
      uni.navigateTo({ url: '/pages/User/mine/setting' });
    },
    toEvaluatePage() {
      uni.navigateTo({ url: '/pages/User/profile/evaluate' });
    },
    handleLogout() {
      if (!this.isLogin) return;
      
      uni.showModal({
        title: '确认退出',
        content: '退出后需重新登录，是否继续？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
            this.isLogin = false;
            this.userInfo = {};
            this.realEvaluateList = [];
            uni.reLaunch({ url: '/pages/login/login' });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 全局容器 */
.mine-container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 100rpx);
  background-color: #f5f7fa;
  box-sizing: border-box;
}

/* 顶部导航 */
.top-nav {
  height: 88rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 99;
}
.nav-title {
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
}

/* 用户信息区 */
.user-info-wrap {
  padding-top: 120rpx;
  padding-bottom: 24rpx;
}
.user-info {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  background-color: #fff;
  margin: 0 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.user-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  border: 2rpx solid #f0f0f0;
  margin-right: 24rpx;
}
.name-id-area {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.unlogin-text {
  font-size: 32rpx;
  color: #666;
}
.login-username {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}
.user-id {
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
}

/* 评价卡片 */
.evaluate-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 24rpx 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}
.card-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}
.view-all {
  font-size: 26rpx;
  color: #5555ff;
  cursor: pointer;
}

/* 评价加载中 */
.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
  color: #5555ff;
  font-size: 26rpx;
}
.loading-text {
  margin-top: 16rpx;
}

/* 评价列表 */
.evaluate-list {
  margin-bottom: 16rpx;
}
.evaluate-item {
  padding: 20rpx 0;
  border-bottom: 1rpx dashed #f0f0f0;
}
.evaluate-item:last-child {
  border-bottom: none;
}

/* 工单信息 */
.order-brief {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;
  font-size: 24rpx;
}
.order-title {
  color: #333;
  font-weight: 500;
}
.order-type {
  color: #5555ff;
  background-color: #f0f8ff;
  padding: 2rpx 12rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
}

/* 评价头部 */
.evaluate-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}
.taker-avatar {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #5555ff;
  color: #fff;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}
.evaluate-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}
.taker-name {
  font-size: 26rpx;
  margin-bottom: 4rpx;
}
.star-rating.small .star {
  font-size: 20rpx;
}
.star.active {
  color: #ffd700;
}
.evaluate-time {
  font-size: 22rpx;
  color: #999;
  margin-left: auto;
}

/* 评价内容 */
.evaluate-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 空评价状态 */
.empty-evaluate {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  color: #999;
}
.empty-icon {
  font-size: 60rpx;
  margin-bottom: 16rpx;
}
.empty-text {
  font-size: 26rpx;
}

/* 功能列表 - 核心修改：增加底部内边距避免被底部导航遮挡 */
.function-list {
  background-color: #fff;
  margin: 0 24rpx 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding-bottom: 120rpx; /* 底部预留空间，大于底部导航高度 */
}
.function-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}
.function-item:last-child {
  border-bottom: none;
}
.function-item:active {
  background-color: #f9f9f9;
}
.item-text {
  font-size: 30rpx;
  color: #333;
  margin-left: 20rpx;
}

/* 退出登录按钮 */
.logout-item {
  background-color: #fff5f5;
}
.logout-text {
  color: #ff4d4f;
}

/* 底部导航 */
.fixed-bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 99;
}
</style>
